package com.miaosha.service.impl;

import com.miaosha.dao.PromoDOMapper;
import com.miaosha.dataobject.PromoDO;
import com.miaosha.error.EnumError;
import com.miaosha.error.ErrorException;
import com.miaosha.model.PromoModel;
import com.miaosha.service.PromoService;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class PromoServiceImpl implements PromoService{

    @Autowired
    private PromoDOMapper promoDOMapper;

    @Override
    public PromoModel getPromoByProductId(Integer productId) throws ErrorException {
        PromoDO promoDO = promoDOMapper.selectByProductId(productId);

        PromoModel promoModel = convertPromoModelFromPromoDe(promoDO);
        if (promoModel == null)  return null;

        if (promoModel.getStartDate().isAfterNow()){
            promoModel.setStatus(1);
        } else if (promoModel.getEndDate().isBeforeNow()){
            promoModel.setStatus(3);
        } else {
            promoModel.setStatus(2);
        }

        return promoModel;
    }

    private PromoModel convertPromoModelFromPromoDe(PromoDO promoDO){
        if (promoDO == null) return null;
        PromoModel promoModel = new PromoModel();
        BeanUtils.copyProperties(promoDO,promoModel);
        promoModel.setStartDate(new DateTime(promoDO.getStartDate()));
        promoModel.setEndDate(new DateTime(promoDO.getEndDate()));
        return promoModel;
    }
}
